<template>
  <div class="app-container">
          <el-card>
        <div slot="header" class="clearfix">
          <span>{{$t('Merchandise_category_sales_data')}}</span>
          <div style="display: inline;float: right;">
            <div style="display: inline;float: right;" class="block">
              <el-date-picker v-model="dateRange" type="datetimerange" :clearable="false"
                :picker-options="pickerOptions" @change="handleDateChange" format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm" :placeholder="$t('Select_dates')" />
            </div>
          </div>
        </div>
        <el-row>
          <el-col :span="12">
            <ve-pie :data="goodsData" :settings="goodsChartSettings" :events="goodsChartEvents" />
            <div align="center">{{$t('商品销售分析')}}</div>
          </el-col>
          <el-col :span="12">
            <ve-pie :data="categoryData" :settings="categoryChartSettings" :events="categoryChartEvents" />
          </el-col>
          <div align="center">{{$t('类目销售分析')}}</div>
        </el-row>
      </el-card>
    <el-card>
      <div slot="header" class="clearfix">
        <span>{{$t('Merchandise_data')}}</span>
      </div>
      <el-row style="margin-bottom: 20px;">
        <el-cascader v-model="queryParam.categoryl3" class="filter-item" clearable :options="categoryList"
          expand-trigger="hover" @change="handleCategoryChange" :placeholder="$t('请选择商品分类')"
          :show-all-levels="false"></el-cascader>
        <el-select v-model="queryParam.goodsId" filterable class="filter-item" :placeholder="$t('请选择商品名称')" clearable>
          <el-option v-for="item in goodsList" :key="item.id" :value="item.id" :label="item.name"></el-option>
        </el-select>
        <el-select v-model="queryParam.orderSource" :placeholder='$t("请选择销售类型")' clearable>
          <el-option :label='$t("APP")' value="1"></el-option>
          <el-option :label='$t("POS")' value="2"></el-option>
        </el-select>
        <el-select v-model="queryParam.isOnSale" :placeholder='$t("请选择商品状态")' clearable>
          <el-option :label='$t("上架")' value="1"></el-option>
          <el-option :label='$t("下架")' value="0"></el-option>
        </el-select>
        <el-select v-model="queryParam.payType" :placeholder='$t("请选择支付方式")' clearable>
          <el-option :label='$t("现金支付")' value="1"></el-option>
          <el-option :label='$t("礼物卡支付")' value="2"></el-option>
          <el-option :label='$t("PayPal支付")' value="3"></el-option>
          <el-option :label='$t("余额支付")' value="4"></el-option>
          <el-option :label='$t("Clover支付")' value="5"></el-option>
          <el-option :label='$t("积分支付")' value="6"></el-option>
        </el-select>
        <el-cascader :placeholder="$t('请选择区域地址')" class="filter-item" v-model="queryParam.regionIds" :options="countrys"
          @active-item-change="handleItemChange" :props="props" clearable filterable></el-cascader>
        <el-select v-model="queryParam.shopId" clearable :placeholder="$t('Please_select_store_')" @change="getData">
          <el-option v-for="item in shops" :key="item.id" :value="item.id" :label="item.name"></el-option>
        </el-select>

        <el-date-picker v-model="queryParam.dateRange"  :placeholder="$t('Select_dates')" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
          align="right" unlink-panels range-separator="——" :start-placeholder='$t("开始日期")' :end-placeholder='$t("结束日期")'
          :picker-options="pickerOptions">
        </el-date-picker>
        <el-button type="primary" plain1 icon="el-icon-search" @click="handleFilter">{{ $t('Search') }}</el-button>
      </el-row>

      <el-card>
        <div class="table-layout">
          <el-row>
            <el-col :span="2" class="table-cell-title">{{$t('总商品数量')}}<i class="el-icon-s-home"></i></el-col>
            <el-col :span="2" class="table-cell-title">{{$t('卖出总件数')}}<i class="el-icon-s-home"></i></el-col>
            <el-col :span="2" class="table-cell-title">{{$t('付款总人数')}}<i class="el-icon-s-release"></i></el-col>
            <el-col :span="3" class="table-cell-title">{{$t('总销售金额')}}</el-col>
            <el-col :span="6" class="table-cell-title">{{$t('总税费')}}</el-col>
            <el-col :span="3" class="table-cell-title">{{$t('退款完成总人数')}}</el-col>
            <el-col :span="3" class="table-cell-title">{{$t('退款商品总数')}}</el-col>
            <el-col :span="3" class="table-cell-title">{{$t('退款总额')}}</el-col>
          </el-row>
          <el-row>
            <el-col :span="2" class="table-cell">{{tatalGoodsData.goodsNum}}</el-col>
            <el-col :span="2" class="table-cell">{{tatalGoodsData.salesNum}}</el-col>
            <el-col :span="2" class="table-cell">{{tatalGoodsData.payUserNum}}</el-col>
            <el-col :span="3" class="table-cell">$ {{NumberUtils.formatFixed2(tatalGoodsData.actualPrice)}}</el-col>
            <el-col :span="6" class="table-cell">
<!--                  <div> ${{(tatalGoodsData.gstTaxPrice + tatalGoodsData.hstTaxPrice + tatalGoodsData.pstTaxPrice).toFixed(2)}} </div>-->
               GST ${{NumberUtils.formatFixed2(tatalGoodsData.gstTaxPrice)}} |
              HST ${{NumberUtils.formatFixed2(tatalGoodsData.hstTaxPrice)}} |
              PST ${{NumberUtils.formatFixed2(tatalGoodsData.pstTaxPrice)}}
          </el-col>
            <el-col :span="3" class="table-cell">{{tatalGoodsData.refundUserNum}}</el-col>
            <el-col :span="3" class="table-cell">{{tatalGoodsData.refundNum}}</el-col>
            <el-col :span="3" class="table-cell">$ {{NumberUtils.formatFixed2(tatalGoodsData.refundActualPrice)}}</el-col>
          </el-row>
        </div>

        <div slot="header" class="clearfix">
          <span>{{$t('Merchandise_sales')}}</span>
        </div>
        <el-row>
          <!-- element-loading-background = "rgba(0, 0, 0, 0.5)"
          element-loading-text = "数据正在计算中"
          element-loading-spinner = "el-icon-loading" -->
          <el-table v-if="listQuery.type == '1'" v-loading="listLoading" :data="list"
          element-loading-spinner = "el-icon-loading"
            :element-loading-text="$t('数据正在计算中')" border fit highlight-current-row>
            <el-table-column align="center" type="index"  :label="$t('序号')"  width="50" />
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-table :data="props.row.items" border size="small" style="width: 100%;">
                  <el-table-column prop="specificationsName" label="规格" align="center" />
                  <el-table-column prop="salesNum" label="卖出件数" align="center" />
                  <el-table-column prop="payUserNum" label="付款人数" align="center" />
                  <el-table-column prop="actualPrice" label="销售金额" align="center">
                    <template slot-scope="scope">
                      $ {{ NumberUtils.formatFixed2(scope.row.actualPrice) }}
                    </template>
                  </el-table-column>
                 <el-table-column label="总税费" align="center">
                   <template slot-scope="scope">
                     GST ${{ NumberUtils.formatFixed2(scope.row.gstTaxPrice) }}<br />
                     HST ${{ NumberUtils.formatFixed2(scope.row.hstTaxPrice) }}<br />
                     PST ${{ NumberUtils.formatFixed2(scope.row.pstTaxPrice) }}
                   </template>
                 </el-table-column>
                  <el-table-column prop="refundUserNum" label="退款人数" align="center" />
                  <el-table-column prop="refundNum" label="退款商品数量" align="center" />
                  <el-table-column prop="refundActualPrice" label="退款金额" align="center">
                    <template slot-scope="scope">
                      $ {{ NumberUtils.formatFixed2(scope.row.refundActualPrice) }}
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('商品分类')" prop="categorylName"/>
            <el-table-column align="center" :label="$t('商品名称')" prop="goodsName" />
            <el-table-column align="center" :label="$t('卖出')+$t('Units')" prop="salesNum" />
            <el-table-column align="center" :label="$t('Number_of_paying_customers')" prop="payUserNum" />
            <el-table-column align="center" :label="$t('销售金额')" prop="actualPrice">
              <template slot-scope="scope">
                $ {{ NumberUtils.formatFixed2(scope.row.actualPrice) }}
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('总税费')"  >
              <template slot-scope="scope">
                <div>GST ${{NumberUtils.formatFixed2(scope.row.gstTaxPrice)}}</div>
                <div>HST ${{NumberUtils.formatFixed2(scope.row.hstTaxPrice)}}</div>
                <div>PST ${{NumberUtils.formatFixed2(scope.row.pstTaxPrice)}}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('退款完成人数')" prop="refundUserNum" />
            <el-table-column align="center" :label="$t('退款商品数量')" prop="refundNum" />
            <el-table-column align="center" :label="$t('退款总额')" prop="refundActualPrice">
              <template slot-scope="scope">
                $ {{ NumberUtils.formatFixed2(scope.row.refundPrice || 0) }}
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('单位')" prop="unit"  />
            <!-- <el-table-column align="center" :label="$t('规格')"  prop="refundNum"  /> -->
            <el-table-column align="center" :label="$t('商品状态')">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isOnSale?'success':'danger'">{{scope.row.isOnSale?"已上架":"一下架"}}</el-tag>
              </template>
            </el-table-column>

          </el-table>
        </el-row>
      <pagination :total="total" :page.sync="queryParam.page" :limit.sync="queryParam.limit" @pagination="getList" />
      </el-card>
<!--      <el-card>
        <span>{{$t('商品浏览量情况( 实时 更新 )')}}</span>
        <el-row>
          <ve-histogram :data="chartData" :extend="extend"></ve-histogram>
        </el-row>
      </el-card>

      <el-card>
        <span>{{$t('商品浏览量情况( 实时 更新 )')}}</span>
        <el-row>
          <ve-bar :data="chartData" :options="chartOptions" style="width: 800px; height: 600px;"></ve-bar>
        </el-row>
      </el-card>-->
    </el-card>

  </div>
</template>

<script>
  import echarts from 'echarts'
  import VePie from 'v-charts/lib/pie.common'
  import VeHistogram from 'v-charts/lib/histogram';
  import VeBar from 'v-charts/lib/bar.common';
  import 'v-charts/lib/style.css';
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import NumberUtils from "@/utils/numberUtils";
  import { goodsStatistics, goodsSalesStatistics, getGoodsBrowser ,goodsSalesStatisticsGeneral} from '@/api/statistics'
  import { allForPerm } from '@/api/shop'
  import { formatDate } from '@/utils/date'
  import { categoryl3, listShopGoodsAll } from '@/api/goods'
  import { listCountryRegion, listSubRegion } from '@/api/region'
  // import {listGoods , } from '@/api/goods'

  export default {
    name: 'goodsStatistics',
    components: { VeHistogram, VePie, VeBar ,Pagination},
    data() {
      const startDate = formatDate(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), 'yyyy-MM-dd hh:mm')
      const endDate = formatDate(new Date(), 'yyyy-MM-dd hh:mm')
      let goodsChartEvents = {
        click: (e) => {
          this.saleDateRange = this.dateRange
          this.getList('1')
        }
      }
      let categoryChartEvents = {
        click: (e) => {
          this.saleDateRange = this.dateRange
          this.getList('2')
        }
      }
      return {
        NumberUtils,
        chartOptions: {
          tooltip: {},
          xAxis: {
            type: 'category',
            data: [],
          },
          yAxis: {
            type: 'value',
          },
          series: [{
            type: 'bar',
            data: [],
          }],
        },
        extend: {
          // 不展示图例lengend
          legend: {
            show: false
          },
          series: {
            itemStyle: {
              // color:'#F4C569',
              // barBorderRadius: 5,如果有normal:{}，则写在这里会没有效果
              //normal有时会和和高亮emphasis:{}成对出现
              normal: {
                barBorderRadius: 5,
                // color:'#F4C569',
                // 颜色渐变效果：需要在使用的组件中import echarts from 'echarts'
                color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: '#FEECB1' },
                    { offset: 1, color: '#F4C569' }
                  ]
                )
              }
            },
            label: {//每个小柱子的提示文字
              show: true,
              position: 'top',
            },
            barWidth: 20,
          }
        },
        chartData: {
          columns: ['商品名称', '商品浏览量', '商品浏览人数'],
          rows: []
        },
        goodsChartEvents,
        categoryChartEvents,
        tatalGoodsData:{}, // 商品总计
        countrys: [], // 区域列表
        props: {
          value: 'id',
          label: 'nameEn',
          children: 'children',
          checkStrictly: true
        },
        total: 0,

        goodsList: [], // 商品集合
        categoryList: [], // 商品级别
        queryParam: {
          page: 0,
          limit: 10,
          shopId: undefined, // 门店id
          categoryl3: undefined, // 商品分类id
          isOnSale: undefined, // 商品状态
          orderSource: undefined, // 销售类型
          payType: undefined, //支付方式
          regionIds: [], // 区域id
          timeHorizon: undefined, // 时间段
          goodsId: undefined, // 商品id
        },
        listQuery: {
          type: '1'
        },
        shops: [],
        dateRange: [startDate, endDate],
        goodsBrowserdateRange: [startDate, endDate],
        saleDateRange: [startDate, endDate],
        activeTable: '1',
        pickerOptions: {
          shortcuts: [{
            text: this.$t('Yesterday'),
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('Last_7_days'),
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('Last_month'),
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        listLoading: false,
        goodsData: {
          columns: ['goods', 'count'],
          rows: []
        },
        categoryData: {
          columns: ['category', 'count'],
          rows: []
        },
        list: [],
        /*      goodsChartEvents: {
                click: this.getList
              },
              categoryChartEvents: {
                click: this.getList
              }*/
        goodsChartSettings: undefined,
        categoryChartSettings: undefined
      }
    },
    created() {
      this.goodsChartSettings = {
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {d}%',
          fontSize: 12
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10,
          smooth: false,
          lineStyle: {
            color: '#666',
            width: 1
          }
        },
        avoidLabelOverlap: true,
        legend: {
          show: true,
          position: 'left'
        }
      }
      this.categoryChartSettings = {
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {d}%',
          fontSize: 12
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10,
          smooth: false,
          lineStyle: {
            color: '#666',
            width: 1
          }
        },
        avoidLabelOverlap: true,
        legend: {
          show: true,
          position: 'left'
        }
      }
      let shopId = this.$route.query.id
      if (shopId) {
        this.queryParam.shopId = shopId
      }
      allForPerm().then(response => {
        this.shops = response.data.data.list
      })
      categoryl3().then(res => {
        this.categoryList = res.data.data
      })
      this.getCountrys()
      this.getData()
      this.getGoodsList()
      // 定时更新数据
      this.timer = setInterval(() => {
        this.goodsBrowser();
      }, 5000); // 每隔 5 秒更新一次数据
    },
    beforeDestroy() {
      // 在组件销毁之前清除定时器
      clearInterval(this.timer);
    },
    methods: {
      getData() {
        let param = {
          shopId: this.queryParam.shopId,
          startTime: this.dateRange[0],
          endTime: this.dateRange[1]
        }
        this.goodsData.rows.splice(0, this.goodsData.rows.length)
        this.categoryData.rows.splice(0, this.categoryData.rows.length)
        goodsStatistics(param).then(response => {
          if (response.data.data) {
            if (response.data.data.orderGoods) {
              response.data.data.orderGoods.forEach(goods => {
                let exist = this.goodsData.rows.find(goods => {
                  if (goods.goods == goods.goodsName) {
                    return goods
                  }
                })
                if (exist) {
                  exist.count = exist.count + goods.number
                } else {
                  this.goodsData.rows.push({
                    goods: goods.goodsName,
                    count: goods.number
                  })
                }
              })
            }
            if (response.data.data.categorys) {
              response.data.data.categorys.forEach(cate => {
                this.categoryData.rows.push({
                  category: cate.categoryName,
                  count: cate.number
                })
              })
            }
          }
        })
        this.getList()
        this.goodsBrowser()
      },
      goodsBrowser() {
        setTimeout(() => {
          getGoodsBrowser().then(res => {
            this.chartData.rows = res.data.data.map(item => ({
              '商品名称': item.name,
              '商品浏览量': item.goodsNum,
              '商品浏览人数': item.userNum
            }));
            this.chartOptions.xAxis.data = this.chartData.rows.map(item => item.name);
            this.chartOptions.series[0].data = this.chartData.rows.map(item => item.goodsNum);
          })
        })
      },
      // 获取表格列表
      getList(type) {
        if (type) {
          this.listQuery.type = type
        }
        this.listLoading = true;
        let param =  this.queryParam;

        // 表格
        goodsSalesStatistics(param).then(response => {
          this.listLoading = false;
          if (!response.data.data) {
            this.list = []
          } else {
            this.list = response.data.data.list
            this.total = response.data.data.total
          }
        })
        // 总计
        goodsSalesStatisticsGeneral(param).then(response => {
          if (!response.data.data) {
            this.tatalGoodsData = {}
          } else {
            this.tatalGoodsData = response.data.data
          }
        })
      },
      handleFilter() {
        console.log("查询参数------------》", this.queryParam)
        this.getList()
      },
      // 添加套餐类目 商品信息 选择商品改变
      packageGoodsChangeSelect(packageGoods) {
        const selectedGoods = this.goodsList.find(goods => goods.id === packageGoods);

        this.packageGoodsForm.goodsId = selectedGoods.id;
      },
      // 查询所有商品
      getGoodsList() {
        listShopGoodsAll().then(response => {
          this.goodsList = response.data.data
        }).catch(() => {
          this.goodsList = []
        })
      },
      // 商品类目列表
      handleCategoryChange(value) {
        this.queryParam.categoryl3 = (value && value.length > 0) ? value[value.length - 1] : '';
      },
      // 区域列表
      getCountrys() {
        listCountryRegion().then(response => {
          this.countrys = response.data.data.list.map(function (country) {
            return _.defaults(country, { children: [] })
          })
        })
      },
      handleItemChange(val) {
        let step = val.length
        let query = {
          id: val[val.length - 1],
          type: 1
        }
        console.log("选择区域", query)
        listSubRegion(query).then(response => {
          let result = this.findObject(this.countrys, val)
          response.data.data.list.forEach(child => {
            if (step <= 1) {
              result.children.push(this._.defaults(child, { children: [] }))
            } else {
              result.children.push(child)
            }
          })
        })
      },
      findObject(arr, ids) {
        // let result = undefined
        for (let i = 0; i <= arr.length - 1; i++) {
          let obj = arr[i]
          if (ids.length == 1 && obj.id == ids[0]) {
            return obj;
          } else if (obj.id == ids[0]) {
            ids.shift()
            return this.findObject(obj.children, ids)
          }
        }
      },
      handleDateChange(dateRange) {
        console.log(dateRange)
        this.getData()
      },
      handlegoodsBrowserDateChange(dateRange) {
        this.goodsBrowser();
      },

      handleSaleDateChange(dateRange) {
        this.getList()
      },
      exportCategory() {

      },
      handleCategoryClick() {

      },
      exportList() {

      },
      handleListClick() {

      }
    }
  }
</script>

<style scoped>
  .table-layout {
    margin-top: 20px;
    border-left: 1px solid #DCDFE6;
    border-top: 1px solid #DCDFE6;
  }

  .table-cell {
    height: 60px;
    line-height: 40px;
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    padding: 10px;
    font-size: 14px;
    color: #606266;
    text-align: center;
    overflow: hidden;
  }

  .table-cell-title {
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    padding: 10px;
    background: #F2F6FC;
    text-align: center;
    font-size: 14px;
    color: #303133;
  }
</style>
